<template>
  <div class="role">
    <PageSearch
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    />
    <PageContent
      :content-config="contentConfig"
      ref="contentRef"
      @edit-click="handleEditClick"
      @new-click="handleNewClick"
    />
    <PageModal :modal-config="modalConfig" ref="modalRef" :other-info="otherInfo">
      <template #menulist>
        <el-tree
          :data="entireMenus"
          show-checkbox
          node-key="id"
          highlight-current
          :props="{ children: 'children', label: 'name' }"
          @check="handleElTreeCheck"
          ref="treeRef"
        >
        </el-tree>
      </template>
    </PageModal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { ElTree } from 'element-plus'
import { storeToRefs } from 'pinia'

import PageModal from '@/components/page-modal/page-modal.vue'
import PageSearch from '@/components/page-search/page-search.vue'
import PageContent from '@/components/page-content/page-content.vue'

import modalConfig from './config/modal.config'
import searchConfig from './config/search.config'
import contentConfig from './config/content.config'

import usePageContent from '@/hooks/usePageContent'
import usePageModal from '@/hooks/usePageModal'

import useMainStore from '@/store/main/main'
import { mapMenuListToIds } from '@/utils/map-menus'
import { nextTick } from 'vue'

// 查询操作, content 的操作
const { contentRef, handleQueryClick, handleResetClick } = usePageContent()
// 点击 content，Modal的操作
const { modalRef, handleNewClick, handleEditClick } = usePageModal(newCallback, editCallback)

// 获取完整菜单
const mainStore = useMainStore()
const { entireMenus } = storeToRefs(mainStore)
// 其它要上传的信息，当选中树形菜单后，获取其对应的id，传入到子组件，通过子组件发送到服务器
const otherInfo = ref({})
// 获取选中的菜单id
function handleElTreeCheck(data1: any, data2: any) {
  const menuList = [...data1.checkedKeys, ...data2.halfCheckedKeys]
  // console.log(data2.checkedKeys)
  otherInfo.value = { menuList }
}

// 树形菜单的回显
const treeRef = ref<InstanceType<typeof ElTree>>()
// 新建数据后 要对菜单的回显清空
// 如果此处用两个 el-tree 则可以不用 nextTick 也能完成
function newCallback() {
  nextTick(() => {
    treeRef.value?.setCheckedKeys([])
  })
}
function editCallback(itemData: any) {
  nextTick(() => {
    const menuIds = mapMenuListToIds(itemData.menuList)
    // setCheckedKeys 是 elementUI里面内置的方法
    treeRef.value?.setCheckedKeys(menuIds)
  })
}
</script>

<style lang="less" scoped>
.role {
}
</style>
